//
//  XPLocation.swift
//  PPKit
//
//  Created by xiaopin on 2019/7/2.
//  Copyright © 2019 PPKit. All rights reserved.
//  https://gitee.com/xiaopindev/PPKit
//  https://github.com/xiaopindev
//  https://xiaopin.cnblogs.com

/*
info.plist必须配置的权限
 
 Privacy - Location Always Usage Description：应用需要您授权定位权限，才可以使用城市定位，定位用于根据城市查询数据
 Privacy - Location When In Use Usage Description：应用需要您授权定位权限，才可以使用城市定位，定位用于根据城市查询数据
 */
import CoreLocation
import HandyJSON

class XPLocationModel: HandyJSON {
    
    required init() {}
    /// 经纬度
    var coordinate:CLLocationCoordinate2D?
    /// ISO标准国家代码
    var ISOCountryCode:String?
    /// 国家名称
    var country:String?
    /// 省份或管理区域
    var administrativeArea:String?
    /// 省份或管理区域次级(中国区没有)
    var subAdministrativeArea:String?
    /// 城市
    var locality:String?
    /// 区县
    var subLocality:String?
    /// 街道
    var thoroughfare:String?
    /// 几号
    var subThoroughfare:String?
    /// 定位地址全文
    var fullAddress:String?
}

/// 定位信息管理类
class XPLocation:NSObject,CLLocationManagerDelegate{
    //MARK: 单例类写法
    static let shared = XPLocation()
    private override init(){}
    
    //MARK: 公开属性
    var detailClosure:((XPLocationModel)->())?
    
    //MARK: 属性
    private var locationManager:CLLocationManager?
    private var singleRequest:Bool = true
    
    //MARK: 方法
    func startLocation(_ singleRequest:Bool = true) -> Self{
        self.singleRequest = singleRequest
        
        locationManager = CLLocationManager()
        locationManager?.delegate = self
        //设置精度
        locationManager?.desiredAccuracy = kCLLocationAccuracyBest
        //不需要定位时暂停定位
        locationManager?.pausesLocationUpdatesAutomatically = true
        //设置定位数据的用途
        locationManager?.activityType = .fitness
        //设置距离筛选器(表示设备至少移动5米才通知delegate)，默认kCLDistanceFilterNone
        locationManager?.distanceFilter = 5.0
        //请求授权
        locationManager?.requestWhenInUseAuthorization()
        //开始定位
        locationManager?.startUpdatingLocation()
        
        return self
    }
    
    func stopLocation(){
        guard let manager = locationManager else{return}
        manager.stopUpdatingLocation()
        locationManager = nil
    }
    
    //MARK: 委托代理
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        switch status {
        case .notDetermined:
            manager.requestWhenInUseAuthorization()
        case .denied:
            showAlert("检测到您已关闭定位权限，请前往设置中开启定位权限")
        default:
            break
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        //获取最新定位
        let newLocation = locations.last
        PPLog("定位信息:\(newLocation)")
        //根据经纬度获取指定地理位置信息，包括国家、城市、区域等
        let geocoder = CLGeocoder()
        geocoder.reverseGeocodeLocation(newLocation!) { [weak self] (placeMarks, error) in
            PPLog("reverseGeocodeLocation:\(String(describing: placeMarks)) ，error：\(String(describing: error))")
            guard let places = placeMarks else{return}
            if places.count == 0 {return}
            let placemark = places.first
            PPLog("""
                国家ISO= \(placemark?.isoCountryCode ?? ""),
                国家名称= \(placemark?.country ?? ""),
                省份= \(placemark?.administrativeArea ?? ""),
                城市= \(placemark?.locality ?? ""),
                区= \(placemark?.subLocality ?? ""),
                街道= \(placemark?.thoroughfare ?? ""),
                街道号= \(placemark?.subThoroughfare ?? ""),
                
                --> Name= \(placemark?.name ?? ""),
                """)

            let location = XPLocationModel()
            location.coordinate = newLocation?.coordinate
            location.ISOCountryCode = placemark?.isoCountryCode
            location.country = placemark?.country
            location.administrativeArea = placemark?.administrativeArea
            location.subAdministrativeArea = placemark?.subAdministrativeArea
            location.locality = placemark?.locality
            location.subLocality = placemark?.subLocality
            location.thoroughfare = placemark?.thoroughfare
            location.subThoroughfare = placemark?.subThoroughfare
            location.fullAddress = "\(placemark?.administrativeArea ?? "")\(placemark?.subAdministrativeArea ?? "")\(placemark?.locality ?? "")\(placemark?.subLocality ?? "")\(placemark?.thoroughfare ?? "")\(placemark?.subThoroughfare ?? "")"
            XPApplication.shared.locationInfo = location
            
            //存储当前城市ID,城市名称，城市短名称
            XPApplication.shared.currentCity = location.locality
            XPApplication.shared.currentCity_ShortName = location.locality?.replacingOccurrences(of: "市", with: "")
            let picker = TLCityPickerController()
            for obj in picker.data {
                let group:TLCityGroup = obj as! TLCityGroup
                for obj2 in group.arrayCitys {
                    let city:TLCity = obj2 as! TLCity
                    if city.cityName == XPApplication.shared.currentCity {
                        XPApplication.shared.currentCityId = city.cityID
                        break
                    }
                }
            }
            if self?.singleRequest == true {
                self?.stopLocation()
            }
            
            self?.detailClosure?(location)
        }
    }
}
